import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:mesh/function/widgets/border_widget.dart';
import '../../function/states/user_state.dart';
import '../../function/states/post_state.dart';
import '../../function/states/follow_state.dart';
import '../../function/states/activity_state.dart';
import '../../function/widgets/toast_widget.dart';
import '../../function/widgets/report_dialog.dart';
import '../../function/widgets/animated_tap_widget.dart';
import '../../function/routes/app_route_manager.dart';

/// 个人中心页面
class UserCenterScreen extends StatefulWidget {
  const UserCenterScreen({super.key});

  @override
  State<UserCenterScreen> createState() => _UserCenterScreenState();
}

class _UserCenterScreenState extends State<UserCenterScreen> {
  bool _visitorSwitchEnabled = true;
  int _currentTabIndex = 0;
  late PageController _pageController;

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: _currentTabIndex);

    // 监听用户状态变化
    UserState.currentUserBeacon.subscribe((currentUser) {
      if (mounted) {
        setState(() {});
      }
    });
    // 监听动态列表变化
    PostState.postListBeacon.subscribe((postList) {
      if (mounted) {
        setState(() {});
      }
    });
    // 监听关注状态变化
    FollowState.userFollowsMapBeacon.subscribe((followsMap) {
      if (mounted) {
        setState(() {});
      }
    });
    // 监听收藏状态变化
    PostState.userFavoritePostsMapBeacon.subscribe((favoritesMap) {
      if (mounted) {
        setState(() {});
      }
    });
    // 监听勋章状态变化
    ActivityState.userBadgeMapBeacon.subscribe((badgeMap) {
      if (mounted) {
        setState(() {});
      }
    });
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  /// 格式化时间显示
  String _formatTimeAgo(DateTime publishTime) {
    final now = DateTime.now();
    final difference = now.difference(publishTime);

    if (difference.inMinutes < 1) {
      return 'Just now';
    } else if (difference.inMinutes < 60) {
      return '${difference.inMinutes} Min Ago';
    } else if (difference.inHours < 24) {
      return '${difference.inHours} Hour${difference.inHours > 1 ? 's' : ''} Ago';
    } else if (difference.inDays < 7) {
      return '${difference.inDays} Day${difference.inDays > 1 ? 's' : ''} Ago';
    } else if (difference.inDays < 30) {
      final weeks = (difference.inDays / 7).floor();
      return '$weeks Week${weeks > 1 ? 's' : ''} Ago';
    } else if (difference.inDays < 365) {
      final months = (difference.inDays / 30).floor();
      return '$months Month${months > 1 ? 's' : ''} Ago';
    } else {
      final years = (difference.inDays / 365).floor();
      return '$years Year${years > 1 ? 's' : ''} Ago';
    }
  }

  @override
  Widget build(BuildContext context) {
    final currentUser = UserState.getCurrentUserInfo();
    final isLoggedIn = UserState.checkLoginStatus();

    if (!isLoggedIn || currentUser == null) {
      return Scaffold(
        body: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/common_bg.png'),
              fit: BoxFit.cover,
            ),
          ),
          child: SafeArea(
            child: Center(
              child: Text('Please login first')
                  .fontSize(18.sp)
                  .textColor(Colors.white)
                  .textAlignment(TextAlign.center),
            ),
          ),
        ),
      );
    }

    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/common_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              // 顶部导航栏（固定）
              _buildTopNavigationBar(),

              // 可滚动的内容区域
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      SizedBox(height: 20.h),

                      // 用户信息区域
                      _buildUserInfoSection(currentUser),

                      SizedBox(height: 20.h),

                      // 统计数据
                      _buildStatsSection(currentUser),

                      SizedBox(height: 20.h),

                      // 访客设置
                      _buildVisitorSettingsSection(),

                      SizedBox(height: 20.h),

                      // Tab切换
                      _buildTabSection(),

                      SizedBox(height: 16.h),

                      // 内容区域（固定高度）
                      _buildContentSection(currentUser),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopNavigationBar() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 0.h),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => AppRouteManager.goBack(),
            child: Icon(Icons.chevron_left, color: Colors.white, size: 26.sp),
          ),
          SizedBox(width: 12.w),
          Text('Personal Center')
              .fontSize(18.sp)
              .textColor(Colors.white)
              .fontFamily(
                GoogleFonts.quicksand(fontWeight: FontWeight.w700).fontFamily,
              )
              .fontWeight(FontWeight.w700),
          Spacer(),
          GestureDetector(
            onTap: () => AppRouteManager.navigateToUserConfig(),
            child: Image.asset(
              'assets/images/setup.png',
              width: 24.w,
              height: 24.w,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建用户信息区域
  Widget _buildUserInfoSection(dynamic currentUser) {
    return [
      // 用户头像
      ClipOval(
        child: Image.asset(
          currentUser.avatar,
          width: 60.w,
          height: 60.w,
          fit: BoxFit.cover,
        ),
      ),
      SizedBox(width: 16.w),
      // 用户信息
      Expanded(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Text(currentUser.userName)
                    .fontSize(18.sp)
                    .fontFamily(
                      GoogleFonts.quicksand(
                        fontWeight: FontWeight.w700,
                      ).fontFamily,
                    )
                    .textColor(Colors.white)
                    .fontWeight(FontWeight.w700),
                SizedBox(width: 8.w),
                _buildUserBadges(currentUser.userId),
              ],
            ),
            SizedBox(height: 4.h),
            GestureDetector(
              onTap: () => AppRouteManager.navigateToUserInfoEdit(),
              child: Text('View Or Edit Personal Information >')
                  .fontSize(12.sp)
                  .textColor(const Color(0xFFFF8A3C))
                  .fontFamily(
                    GoogleFonts.quicksand(
                      fontWeight: FontWeight.w500,
                    ).fontFamily,
                  )
                  .fontWeight(FontWeight.w500),
            ),
          ],
        ),
      ),
      // 星星按钮
      AnimatedTapWidget(
        onTap: () => AppRouteManager.navigateToFavoriteEncyclopedia(),
        child: Container(
          width: 36.w,
          height: 36.w,
          padding: EdgeInsets.all(10.w),
          decoration: BoxDecoration(
            color: const Color(0xFFFF8A3C),
            borderRadius: BorderRadius.circular(12.r),
          ),
          child: Center(
            child: Image.asset(
              'assets/images/star2.png',
              width: 20.w,
              height: 20.w,
            ),
          ),
        ),
      ),
    ].toRow().paddingSymmetric(horizontal: 16.w);
  }

  /// 构建统计数据区域
  Widget _buildStatsSection(dynamic currentUser) {
    final followCount = FollowState.getFollowCount(currentUser.userId);
    final followerCount = FollowState.getFollowerCount(currentUser.userId);

    return [
      _buildStatItem('$followCount', 'Follow'),
      _buildStatItem('$followerCount', 'Following'),
      _buildStatItem('24', 'Visitor'),
    ].toRow(mainAxisAlignment: MainAxisAlignment.spaceEvenly);
  }

  /// 构建单个统计项
  Widget _buildStatItem(String count, String label) {
    return Column(
      children: [
        Text(count)
            .fontSize(16.sp)
            .textColor(Colors.white)
            .fontFamily(
              GoogleFonts.quicksand(fontWeight: FontWeight.w700).fontFamily,
            )
            .fontWeight(FontWeight.w700),
        Text(label)
            .fontSize(13.sp)
            .textColor(Colors.white.withOpacity(0.8))
            .fontFamily(
              GoogleFonts.quicksand(fontWeight: FontWeight.w500).fontFamily,
            )
            .fontWeight(FontWeight.w500),
      ],
    );
  }

  /// 构建访客设置区域
  Widget _buildVisitorSettingsSection() {
    return Container(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 10.h),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [const Color(0xFF855516), const Color(0xFF852E11)],
              begin: Alignment.centerLeft,
              end: Alignment.centerRight,
            ),
            borderRadius: BorderRadius.circular(12.r),
          ),
          child: Row(
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('Visitor')
                        .fontSize(16.sp)
                        .textColor(Colors.white)
                        .fontWeight(FontWeight.w600),
                    SizedBox(height: 4.h),
                    Text('Allow Strangers To View The Homepage')
                        .fontSize(12.sp)
                        .textColor(Colors.white.withOpacity(0.7))
                        .fontWeight(FontWeight.w400),
                  ],
                ),
              ),
              Switch(
                value: _visitorSwitchEnabled,
                onChanged: (value) {
                  setState(() {
                    _visitorSwitchEnabled = value;
                  });
                  ToastWidget.showSuccess(
                    value
                        ? 'No one can view your homepage.'
                        : 'Anyone can view your homepage.',
                  );
                },
                activeColor: Colors.white,
                activeTrackColor: const Color(0xFFFF8A3C),
                inactiveThumbColor: Colors.white,
                inactiveTrackColor: Colors.white.withOpacity(0.3),
              ),
            ],
          ),
        )
        .configBorderWidget(
          borderColor: Colors.white,
          borderWidth: 1.w,
          borderRadius: 12.r,
        )
        .paddingHorizontal(16.w);
  }

  /// 构建Tab切换区域
  Widget _buildTabSection() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),

      child: Row(
        children: [
          // 第一个Tab - 靠左对齐
          GestureDetector(
            onTap: () {
              setState(() => _currentTabIndex = 0);
              _pageController.animateToPage(
                0,
                duration: Duration(milliseconds: 300),
                curve: Curves.easeInOut,
              );
            },
            child: Text('The Updates I Posted')
                .fontSize(16.sp)
                .textColor(
                  _currentTabIndex == 0
                      ? Colors.white
                      : Colors.white.withOpacity(0.7),
                )
                .fontFamily(
                  GoogleFonts.quicksand(fontWeight: FontWeight.w700).fontFamily,
                )
                .fontWeight(FontWeight.w700)
                .textAlignment(TextAlign.center),
          ),
          SizedBox(width: 20.w),
          // 第二个Tab - 靠左对齐
          GestureDetector(
            onTap: () {
              setState(() => _currentTabIndex = 1);
              _pageController.animateToPage(
                1,
                duration: Duration(milliseconds: 300),
                curve: Curves.easeInOut,
              );
            },
            child: Text('Like')
                .fontSize(16.sp)
                .textColor(
                  _currentTabIndex == 1
                      ? Colors.white
                      : Colors.white.withOpacity(0.7),
                )
                .fontFamily(
                  GoogleFonts.quicksand(fontWeight: FontWeight.w700).fontFamily,
                )
                .fontWeight(FontWeight.w700)
                .textAlignment(TextAlign.center),
          ),
          // 占位空间，让Tab靠左
          Spacer(),
        ],
      ),
    );
  }

  /// 构建内容区域
  Widget _buildContentSection(dynamic currentUser) {
    // 获取两个Tab的数据
    final publishedPosts = PostState.getPostsByUserId(currentUser.userId);
    final favoritePosts = PostState.getUserFavoritePosts(currentUser.userId);

    // 计算最大高度，确保两个Tab高度一致
    final maxPostsCount = [
      publishedPosts.length,
      favoritePosts.length,
    ].reduce((a, b) => a > b ? a : b);
    final minHeight = maxPostsCount * 310.h; // 每个卡片大约300高度

    return SizedBox(
      height: minHeight > 0 ? minHeight : 400.h, // 最小高度400
      child: PageView(
        controller: _pageController,
        onPageChanged: (index) {
          setState(() {
            _currentTabIndex = index;
          });
        },
        children: [
          // 发布的动态Tab
          _buildTabContent(publishedPosts, 'No posts yet', 0),
          // 收藏的动态Tab
          _buildTabContent(favoritePosts, 'No favorites yet', 1),
        ],
      ),
    ).paddingHorizontal(16.w);
  }

  /// 构建Tab内容
  Widget _buildTabContent(
    List<dynamic> posts,
    String emptyMessage,
    int tabIndex,
  ) {
    if (posts.isEmpty) {
      return _buildEmptyState(emptyMessage);
    }

    return SingleChildScrollView(
      physics: NeverScrollableScrollPhysics(), // 禁止纵向滑动
      child: Column(
        children: [
          for (int index = 0; index < posts.length; index++)
            _buildPostCard(posts[index], tabIndex),
        ],
      ),
    );
  }

  /// 构建空状态页面
  Widget _buildEmptyState(String message) {
    return Padding(
      padding: EdgeInsets.all(40.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          // 空状态图片
          Image.asset('assets/images/empty.png', width: 120.w, height: 120.w),

          SizedBox(height: 24.h),

          // 空状态标题
          Text('No Content Yet')
              .fontSize(20.sp)
              .textColor(Colors.white)
              .fontWeight(FontWeight.w700)
              .fontFamily(
                GoogleFonts.quicksand(fontWeight: FontWeight.w700).fontFamily,
              )
              .textAlignment(TextAlign.center),

          SizedBox(height: 12.h),

          // 空状态描述
          Text(message)
              .fontSize(14.sp)
              .textColor(Colors.white.withOpacity(0.7))
              .fontFamily(
                GoogleFonts.quicksand(fontWeight: FontWeight.w500).fontFamily,
              )
              .textAlignment(TextAlign.center),
        ],
      ),
    );
  }

  /// 构建动态卡片
  Widget _buildPostCard(dynamic post, int tabIndex) {
    final userInfo = PostState.getUserInfo(post.userId);
    final userName = userInfo?['userName'] ?? 'Guest';
    final userAvatar = userInfo?['userAvatar'] ?? 'assets/images/avatar1.png';

    // 获取当前登录用户信息
    final currentUser = UserState.getCurrentUserInfo();
    final isLoggedIn = UserState.checkLoginStatus();
    final currentUserId = currentUser?.userId ?? '';

    // 检查是否已关注该用户
    final isFollowing = FollowState.isFollowing(currentUserId, post.userId);

    // 检查是否已收藏该动态
    final isFavorited = PostState.isPostFavorited(currentUserId, post.postId);

    // 判断是否为用户自己的动态
    final isOwnPost = currentUserId == post.userId;

    return GestureDetector(
      onTap: () => AppRouteManager.navigateToPostDetail(post.postId),
      child: Container(
        margin: EdgeInsets.only(bottom: 20.h),
        child: AspectRatio(
          aspectRatio: 343 / 274,
          child: Container(
            decoration: BoxDecoration(
              color: const Color(0xFF663507),
              borderRadius: BorderRadius.circular(16.r),
            ),
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 12.h),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 用户信息头部
                  Row(
                    children: [
                      // 用户头像
                      ClipOval(
                        child: Image.asset(
                          userAvatar,
                          width: 40.w,
                          height: 40.w,
                          fit: BoxFit.cover,
                        ),
                      ),
                      SizedBox(width: 12.w),
                      // 用户名和时间
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(userName)
                                .fontSize(16.sp)
                                .textColor(Colors.white)
                                .fontWeight(FontWeight.w800)
                                .fontFamily(
                                  GoogleFonts.quicksand(
                                    fontWeight: FontWeight.w800,
                                  ).fontFamily,
                                ),
                            Text(_formatTimeAgo(post.publishTime))
                                .fontSize(12.sp)
                                .textColor(Colors.white)
                                .fontFamily(
                                  GoogleFonts.quicksand(
                                    fontWeight: FontWeight.w600,
                                  ).fontFamily,
                                ),
                          ],
                        ),
                      ),
                      // 根据是否为用户自己的动态显示不同按钮
                      if (!isOwnPost) ...[
                        // Follow按钮 - 只对别人的动态显示
                        GestureDetector(
                          onTap: () {
                            if (!isLoggedIn) {
                              ToastWidget.showWarning(
                                'Please login to follow users',
                              );
                              return;
                            }

                            // 切换关注状态
                            FollowState.toggleFollow(
                              currentUserId,
                              post.userId,
                            );
                          },
                          child: Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 12.w,
                              vertical: 6.h,
                            ),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(32.r),
                            ),
                            child: AnimatedContainer(
                              duration: Duration(milliseconds: 300),
                              curve: Curves.easeInOut,
                              padding: EdgeInsets.symmetric(
                                horizontal: 12.w,
                                vertical: 6.h,
                              ),
                              decoration: BoxDecoration(
                                color:
                                    isFollowing
                                        ? const Color(0xFF854914)
                                        : Colors.white,
                                borderRadius: BorderRadius.circular(32.r),
                                border: Border.all(
                                  color:
                                      isFollowing
                                          ? const Color(0xFF854914)
                                          : Colors.white,
                                  width: 1.w,
                                ),
                              ),
                              child: AnimatedSwitcher(
                                duration: Duration(milliseconds: 200),
                                transitionBuilder: (
                                  Widget child,
                                  Animation<double> animation,
                                ) {
                                  return FadeTransition(
                                    opacity: animation,
                                    child: ScaleTransition(
                                      scale: animation,
                                      child: child,
                                    ),
                                  );
                                },
                                child: Row(
                                  key: ValueKey(isFollowing),
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    AnimatedSwitcher(
                                      duration: Duration(milliseconds: 200),
                                      child: Image.asset(
                                        key: ValueKey(isFollowing),
                                        isFollowing
                                            ? 'assets/images/unfollow.png'
                                            : 'assets/images/follow.png',
                                        width: 14.w,
                                        height: 14.w,
                                        color:
                                            isFollowing
                                                ? Colors.white
                                                : const Color(0xFFFF8A3C),
                                      ),
                                    ),
                                    SizedBox(width: 4.w),
                                    AnimatedDefaultTextStyle(
                                      duration: Duration(milliseconds: 200),
                                      style: TextStyle(
                                        fontSize: 14.sp,
                                        color:
                                            isFollowing
                                                ? Colors.white
                                                : const Color(0xFFFF8A3C),
                                        fontFamily:
                                            GoogleFonts.quicksand(
                                              fontWeight: FontWeight.w600,
                                            ).fontFamily,
                                        fontWeight: FontWeight.w600,
                                      ),
                                      child: Text(
                                        isFollowing ? 'Unfollow' : 'Follow',
                                        maxLines: 2,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ],
                  ),

                  SizedBox(height: 12.h),

                  // 动态内容
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 文字内容
                        Text(
                              post.content.length > 100
                                  ? '${post.content.substring(0, 100)}...'
                                  : post.content,
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                            )
                            .fontSize(12.sp)
                            .fontFamily(
                              GoogleFonts.quicksand(
                                fontWeight: FontWeight.w700,
                              ).fontFamily,
                            )
                            .textColor(Colors.white)
                            .textAlignment(TextAlign.left),

                        SizedBox(height: 8.h),

                        // 媒体画廊（图片和视频缩略图）
                        if (post.mediaUrls.isNotEmpty)
                          Expanded(
                            child: Container(
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(10.r),
                              ),
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(10.r),
                                child: Row(
                                  children: [
                                    // 固定显示3个位置
                                    for (int i = 0; i < 3; i++) ...[
                                      Expanded(
                                        child: Container(
                                          margin: EdgeInsets.only(right: 4.w),
                                          decoration: BoxDecoration(
                                            borderRadius: BorderRadius.circular(
                                              8.r,
                                            ),
                                            color:
                                                i < post.mediaUrls.length
                                                    ? null
                                                    : Colors.transparent,
                                            image:
                                                i < post.mediaUrls.length
                                                    ? DecorationImage(
                                                      image: AssetImage(
                                                        post.isVideoAtIndex(
                                                                  i,
                                                                ) &&
                                                                post.getVideoThumbnailAtIndex(
                                                                      i,
                                                                    ) !=
                                                                    null
                                                            ? post
                                                                .getVideoThumbnailAtIndex(
                                                                  i,
                                                                )!
                                                            : post.mediaUrls[i],
                                                      ),
                                                      fit: BoxFit.cover,
                                                    )
                                                    : null,
                                          ),
                                          child:
                                              i < post.mediaUrls.length &&
                                                      post.isVideoAtIndex(i)
                                                  ? Stack(
                                                    children: [
                                                      Center(
                                                        child: Image.asset(
                                                          'assets/images/play.png',
                                                          width: 24.w,
                                                          height: 24.w,
                                                        ),
                                                      ),
                                                    ],
                                                  )
                                                  : null,
                                        ),
                                      ),
                                    ],
                                  ],
                                ),
                              ),
                            ),
                          ),
                      ],
                    ),
                  ),

                  SizedBox(height: 8.h),

                  // 底部操作栏
                  Container(
                    width: double.infinity,
                    height: 44.h,
                    padding: EdgeInsets.symmetric(horizontal: 16.w),
                    decoration: ShapeDecoration(
                      color: const Color(0xFF854914),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(14.r),
                      ),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        // 点赞和评论
                        Row(
                          children: [
                            GestureDetector(
                              onTap: () {
                                if (!isLoggedIn) {
                                  ToastWidget.showWarning(
                                    'Please login to favorite posts',
                                  );
                                  return;
                                }

                                // 切换收藏状态
                                PostState.togglePostFavorite(
                                  currentUserId,
                                  post.postId,
                                );
                              },
                              child: Row(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  AnimatedSwitcher(
                                    duration: Duration(milliseconds: 200),
                                    transitionBuilder: (
                                      Widget child,
                                      Animation<double> animation,
                                    ) {
                                      return ScaleTransition(
                                        scale: animation,
                                        child: FadeTransition(
                                          opacity: animation,
                                          child: child,
                                        ),
                                      );
                                    },
                                    child: Image.asset(
                                      key: ValueKey(isFavorited),
                                      isFavorited
                                          ? 'assets/images/like-fill.png'
                                          : 'assets/images/like.png',
                                      width: 20.w,
                                      height: 20.w,
                                    ),
                                  ),
                                  SizedBox(width: 4.w),
                                  AnimatedDefaultTextStyle(
                                    duration: Duration(milliseconds: 200),
                                    style: TextStyle(
                                      fontSize: 14.sp,
                                      color: Colors.white,
                                      fontFamily:
                                          GoogleFonts.quicksand(
                                            fontWeight: FontWeight.w600,
                                          ).fontFamily,
                                      fontWeight: FontWeight.w600,
                                    ),
                                    child: Text('${post.favoriteCount}'),
                                  ),
                                ],
                              ),
                            ),
                            SizedBox(width: 16.w),
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Image.asset(
                                  'assets/images/comment.png',
                                  width: 20.w,
                                  height: 20.w,
                                ),
                                SizedBox(width: 4.w),
                                Text('${post.commentCount}')
                                    .fontSize(14.sp)
                                    .textColor(Colors.white)
                                    .fontFamily(
                                      GoogleFonts.quicksand(
                                        fontWeight: FontWeight.w600,
                                      ).fontFamily,
                                    ),
                              ],
                            ),
                          ],
                        ),
                        // 根据是否为用户自己的动态显示不同按钮
                        if (isOwnPost) ...[
                          // 删除按钮 - 只对自己的动态显示
                          GestureDetector(
                            onTap: () => _showDeleteDialog(post),
                            child: Icon(
                              Icons.delete_outline,
                              color: Colors.white,
                              size: 20.w,
                            ),
                          ),
                        ] else ...[
                          // 举报按钮 - 只对别人的动态显示
                          GestureDetector(
                            onTap: () => _showReportDialog(post),
                            child: Image.asset(
                              'assets/images/report.png',
                              width: 20.w,
                              height: 20.w,
                            ),
                          ),
                        ],
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 显示删除确认对话框
  void _showDeleteDialog(dynamic post) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: const Color(0xFF663507),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16.r),
            side: BorderSide(color: const Color(0xFFFF8A3C), width: 1.w),
          ),
          title: Text('Delete Post')
              .fontSize(18.sp)
              .textColor(Colors.white)
              .fontWeight(FontWeight.w700)
              .textAlignment(TextAlign.center),
          content: Text(
                'Are you sure you want to delete this post? This action cannot be undone.',
              )
              .fontSize(14.sp)
              .textColor(Colors.white.withOpacity(0.8))
              .textAlignment(TextAlign.center),
          actions: [
            Row(
              children: [
                Expanded(
                  child: GestureDetector(
                    onTap: () => Navigator.of(context).pop(),
                    child: Container(
                      padding: EdgeInsets.symmetric(vertical: 12.h),
                      decoration: BoxDecoration(
                        color: Colors.white.withOpacity(0.2),
                        borderRadius: BorderRadius.circular(8.r),
                      ),
                      child: Text('Cancel')
                          .fontSize(14.sp)
                          .textColor(Colors.white)
                          .fontWeight(FontWeight.w600)
                          .textAlignment(TextAlign.center),
                    ),
                  ),
                ),
                SizedBox(width: 12.w),
                Expanded(
                  child: GestureDetector(
                    onTap: () {
                      Navigator.of(context).pop();
                      _deletePost(post);
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(vertical: 12.h),
                      decoration: BoxDecoration(
                        color: const Color(0xFFFF4444),
                        borderRadius: BorderRadius.circular(8.r),
                      ),
                      child: Text('Delete')
                          .fontSize(14.sp)
                          .textColor(Colors.white)
                          .fontWeight(FontWeight.w600)
                          .textAlignment(TextAlign.center),
                    ),
                  ),
                ),
              ],
            ),
          ],
        );
      },
    );
  }

  /// 删除动态
  void _deletePost(dynamic post) {
    PostState.removePost(post.postId);
    ToastWidget.showSuccess('Post deleted successfully');
    setState(() {}); // 刷新页面
  }

  /// 显示举报对话框
  void _showReportDialog(dynamic post) {
    ReportDialog.show(
      context,
      title: 'Report Post',
      content: 'Please select a reason for reporting this post',
      onReportSuccess: () => _reportAndRemovePost(post),
    );
  }

  /// 举报并删除动态
  void _reportAndRemovePost(dynamic post) {
    // 从收藏列表中移除
    final currentUser = UserState.getCurrentUserInfo();
    if (currentUser != null) {
      PostState.togglePostFavorite(currentUser.userId, post.postId);
    }

    // 删除动态
    PostState.removePost(post.postId);

    ToastWidget.showSuccess('You won\'t see this post again.');
    setState(() {}); // 刷新页面
  }

  /// 构建用户勋章显示
  Widget _buildUserBadges(String userId) {
    final userBadges = ActivityState.getUserBadges(userId);
    if (userBadges.isEmpty) {
      return const SizedBox.shrink();
    }

    return Row(
      children:
          userBadges.map((activityId) {
            final activity = ActivityState.getActivityById(activityId);
            if (activity == null) return const SizedBox.shrink();

            return Container(
              margin: EdgeInsets.only(right: 4.w),
              child: Image.asset(
                activity.badgeImageUrl,
                width: 16.w,
                height: 16.w,
                fit: BoxFit.cover,
              ),
            );
          }).toList(),
    );
  }
}
